package cn.topcode.unicorn.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class Base64Util {
    // 加密
    public static String encodeFromString(String str) {
        byte[] b = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            return encode(b);
        }
        return null;
    }

    public static String encode(byte[] b) {
        if (b != null) {
            return new BASE64Encoder().encode(b);
        }
        return null;
    }

    public static byte[] decode(String s) {
        byte[] b = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return b;
    }

    // 解密
    public static String decodeToString(String s) {
        byte[] b = decode(s);
        if(b != null) {
            return new String(b, Charset.forName("utf-8"));
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(encodeFromString("hellowolrd"));
    }
}